package AtomicInteger_9;
import java.util.concurrent.atomic.AtomicInteger;
public class 基础计数器_多线程安全计数 {
    private static AtomicInteger counter = new AtomicInteger(0);
    public static void main(String[] args) {
        final int THREAD_COUNT = 20;
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((long)(Math.random() * 100)); // 模拟处理时间
                        int newValue = counter.incrementAndGet();
                        System.out.println(Thread.currentThread().getName() + " 增加计数到: " + newValue);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "线程-" + i).start();
        }
        // 等待所有线程完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终计数值: " + counter.get());
    }
}